<template>
  <section class="f-order-sale">
    <div class="w-card my-content-box" v-if="!isDetail">
      <div class="title-box">
        <span class="title-text">加盟订单</span>
        <div style="margin-left:auto;">
          <el-button type="primary" plain @click="importHandle()">导入</el-button>
          <el-button @click="setOrderJoinDown()">导出</el-button>
        </div>
      </div>
      <div class="my-search-box">
        <div>
          <span>订单ID：</span>
          <el-input v-model="searchForm.sysOrderId" clearable placeholder="请输入订单ID" />
        </div>
        <div>
          <span>关联商户：</span>
          <el-select v-model="searchForm.shopId" clearable>
            <el-option v-for="item in shopList" :key="item.shopId" :label="item.shopName" :value="item.shopId" />
          </el-select>
        </div>
        <div>
          <span>订单状态：</span>
          <el-select v-model="searchForm.orderStatus" clearable>
            <el-option v-for="item in orderStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
      <div class="my-search-box">
        <div>
          <span>商品：</span>
          <el-select v-model="searchForm.goodsId" clearable @change="getOrderJoinPackage">
            <el-option v-for="item in goodsList" :key="item.goodsId" :label="item.goodsName" :value="item.goodsId" />
          </el-select>
        </div>
        <div>
          <span>套餐：</span>
          <el-select v-model="searchForm.packageId" clearable>
            <el-option v-for="item in packageList" :key="item.packageId" :label="item.packageName" :value="item.packageId" />
          </el-select>
        </div>
        <div>
          <span>用户码：</span>
          <el-input v-model="searchForm.userCode" clearable placeholder="请输入用户码" />
        </div>
        <div>
          <span>收件人电话：</span>
          <el-input v-model="searchForm.receivePhone" clearable placeholder="请输入收件人电话" />
        </div>
      </div>
      <div class="my-search-box">
        <div class="datebox">
          <span>下单时间：</span>
          <el-date-picker v-model="searchForm.date" type="datetimerange" value-format="x" start-placeholder="开始时间"
            end-placeholder="结束时间" @change="(e) => {console.log(e)}" />
        </div>
        <div class="f-ml-20">
          <el-button @click="searchHandle" type="primary">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </div>
      </div>
      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" stripe>
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="orderId" label="订单id" align="center">
            <template v-slot="scope">
              <el-link style="fontSize:12px" type="primary" @click="lookDetail(scope.row.sysOrderId)">
                {{ scope.row.sysOrderId || '' }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" align="center">
            <template v-slot="scope">
              {{ orderStatus[scope.row.orderStatus] }}
            </template>
          </el-table-column>
          <el-table-column prop="shopName" label="关联商户" align="center">
            <template v-slot="scope">
              {{ scope.row.shopName || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="订单商品" width="280">
            <template v-slot="scope">
              <div>{{ scope.row.goodsName || '--' }}</div>
              <div class="f-flex">
                <p>套餐：</p>
                <p class="f-flex-1">{{ scope.row.packageGuigeParam || '' }}</p>
              </div>
              <div class="f-flex">
                <p>套餐：</p>
                <p class="f-flex-1">{{ scope.row.packageName || '' }}</p>
              </div>
              <div class="f-flex">
                <p>用户码：</p>
                <p class="f-flex-1">{{ scope.row.userCode || '' }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="支付信息" width="250">
            <template v-slot="scope">
              <div class="g-flex-ct">
                <p>支付金额：</p>
                <p style="color:#FF4040">¥ {{ scope.row.payMoney/100 || '--' }}</p>
              </div>
              <div class="g-flex-ct">
                <p>支付时间：</p>
                <p>{{ getDateTime(scope.row.payTime)[6] || '' }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="物流信息" width="280">
            <template v-slot="scope">
              <div>{{ scope.row.receiverName || '' }} {{ scope.row.receivePhone || '' }}</div>
              <div>{{ scope.row.receiveAddress || '' }}</div>
              <div class="g-flex-ct">
                <p>物流信息：</p>
                <p>{{ scope.row.logisticsNum || '' }} {{ scope.row.logisticsName || ''}}</p>
              </div>
              <div class="g-flex-ct">
                <p>发货时间：</p>
                <p>{{ scope.row.logistStartTime? getDateTime(scope.row.logistStartTime)[6]: '--' }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="下单时间" align="center">
            <template v-slot="scope">
              {{ getDateTime(scope.row.createTime)[6] || '--' }}
            </template>
          </el-table-column>
        </el-table>
        <div class="my-table-footer">
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 导入弹窗 -->
    <Upload ref="uploadRef" v-if="off.upload" :uploadForm="uploadForm" @handleUploadSuccess="importSuccess"
      @handleUploadCancel="off.upload = false" />

    <router-view></router-view>
  </section>
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import Upload from '@/components/Upload.vue'
import api from '../api'

export default {
  components: { Upload },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const uploadRef = ref(null)

    const state = reactive({
      off: {
        upload: false,
      },
      isDetail: false,

      searchForm: {
        "goodsId": "",
        "orderStatus": "",
        "packageId": "",
        "receivePhone": "",
        "receiverName": "",
        "shopId": "",
        "submitType": "",
        "sysOrderId": ""
      },

      tableHeight: 0,
      tableData: [],
      page: 1,
      size: 10,
      total: 0,

      orderStatusOptions: [
        { value: 5, label: '待支付' },
        { value: 10, label: '已支付' },
        { value: 20, label: '待发货' },
        { value: 30, label: '已发货' },
        { value: 40, label: '已收货' },
        { value: 41, label: '拒收' },
        { value: 100, label: '异常待处理' },
        { value: 110, label: '超时关闭' },
        { value: 120, label: '订单关闭' },
        { value: 130, label: '已退款' },
      ],
      orderStatus: {
        '5': '待支付',
        '10': '已支付',
        '20': '待发货',
        '30': '已发货',
        '40': '已收货',
        '41': '拒收',
        '100': '异常待处理',
        '110': '超时关闭',
        '120': '订单关闭',
        '130': '已退款',
      },

      goodsList: [],
      packageList: [],
      shopList: [],

      uploadForm: {
        dialogTitle: '导入加盟订单',
        action: '/eas/manage/order/join/upload'
      }
    })

    watch(() => route.path, (newVal, oldVal) => {
      setIsDetail()
    })

    function setIsDetail() {
      state.isDetail = (route.path != '/orderJoin')
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {}
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
        createTimeMin: state.searchForm.date && state.searchForm.date[0],
        createTimeMax: state.searchForm.date && state.searchForm.date[1],
        orderBy: 'id desc',
      }
      api.orderJoinList(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.list
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function lookDetail(sysOrderId) {
      router.push({ path: '/orderJoin/detail', query: { sysOrderId } })
    }

    const getOrderJoinGoods = () => {
      api.orderJoinGoods().then(res => {
        state.goodsList = res.data
      })
    }

    const getOrderJoinPackage = (goodsId) => {
      state.packageList = []
      state.searchForm.packageId = ''
      let json = {
        goodsId
      }
      api.orderJoinPackage(json).then(res => {
        state.packageList = res.data
      })
    }

    const setOrderJoinDown = () => {
      const obj = {
        responseType: 'blob',
        ...state.searchForm,
        createTimeMin: state.searchForm.date && state.searchForm.date[0],
        createTimeMax: state.searchForm.date && state.searchForm.date[1],
      }
      api.orderJoinDown(obj).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    //导入成功
    function importSuccess() {
      state.page = 1
      getTableData()
    }

    function importHandle() {
      state.off.upload = true
      nextTick(() => {
        uploadRef.value.off.dialog = true
      })
    }

    const getShopAll = () => {
      api.shopAll().then(res => {
        state.shopList = res.data
      })
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 390
      setIsDetail()
      getTableData()
      getOrderJoinGoods()
      getShopAll()
    })

    return {
      ...toRefs(state),
      uploadRef,
      searchHandle,
      resetHandle,
      lookDetail,
      handleCurrentChange,
      handleSizeChange,
      getDateTime,
      getOrderJoinPackage,
      setOrderJoinDown,
      importSuccess,
      importHandle,
    }
  }
}
</script>

<style lang="scss" scoped>
.f-order-sale {
  .my-content-box {
    box-sizing: border-box;
    padding: 20px;

    > .title-box {
      display: flex;
      align-items: center;

      > .title-text {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .my-search-box {
      box-sizing: border-box;
      padding: 20px 20px 20px 0;
      padding-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;

      > div {
        width: 300px;
        display: flex;
        align-items: center;

        > span {
          flex-shrink: 0;
          width: 90px;
          text-align: right;
        }
      }

      .datebox {
        width: 400px;
      }
    }

    .my-table-box {
      margin-top: 20px;

      .table-handle-box {
        display: flex;
        justify-content: space-around;
        align-items: center;
      }

      .my-table-footer {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
}
</style>